﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crosland.Automotriz.Logic.Linq;
using Crosland.Automotriz.Logic.ControlExeption;
using Microsoft.Reporting.WebForms;
using System.Security.Principal;
using System.Configuration;
using System.Net;
using DevExpress.Web.ASPxGridView;
using System.Drawing;


namespace Crosland.Automotriz.Web.Repuestos
{
    public partial class wFrmPronosticoImportacionAprobacionListarDetalle : System.Web.UI.Page
    {
        string idNegocio = ConfigurationManager.AppSettings["Negocio"];
        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack == false)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", "JavaScript:confirmSubmitResult();", true);
                ListaDetalle();
                if (Session["nro_pronostico"] != null && Session["FECHA_GEN"] != null)
                {
                    lblTitulo.Text = "- Nro.Pronóstico: " + Session["nro_pronostico"].ToString() + "   Fecha de pedido: " + Convert.ToDateTime(Session["FECHA_GEN"]).ToShortDateString();
                }
             }
        }


        private void ListaDetalle()
        {

            try
            {
                ActualizarPedidoLogic actualizapedido = new ActualizarPedidoLogic();
                dgDetallePedido.DataSource = actualizapedido.listar(Convert.ToInt32(Session["nro_pronostico"]));
                dgDetallePedido.DataBind();
            }
            catch (DataException ex)
            {
                GuardarExceptionLog(ex.Message, ex, "ListaDetalle");
                MensajesError(ex.Message, ex, "ListaDetalle");
            }
            catch (RunException e)
            {
                GuardarExceptionLog(e.Message, e, "ListaDetalle");
                MensajesError(e.Message, e, "ListaDetalle");
            }


        }

        protected void dgDetallePedido_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "Total")
            {
                decimal price = (decimal)e.GetListSourceFieldValue("cant_sug_real");
                decimal quantity = (decimal)e.GetListSourceFieldValue("fob_me");
                e.Value = price * quantity;
            }
        }



        protected void dgDetallePedido_PageIndexChanged(object sender, EventArgs e)
        {
            ListaDetalle();
        }

        private void GuardarExceptionLog(String msgUsu, Exception ex, String metError)
        {
            try
            {
                String msgReal, fhError, pagError, codUsu;
                msgReal = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                pagError = new System.IO.FileInfo(Page.Request.Url.AbsolutePath).Name;
                codUsu = Session["User"].ToString();
                fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                int number = 0;
                for (int i = 0; i < trace.FrameCount; i++)
                {
                    System.Diagnostics.StackFrame sf = trace.GetFrame(i);
                    number = sf.GetFileLineNumber();
                }
                fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                new Logg().ErrorLog(Server.MapPath("~/Logs/ErrorLog.csv"), msgUsu, msgReal, pagError, metError, codUsu, number);
            }
            catch (DataException e)
            {

                MensajesError(e.Message, e, "GuardarExceptionLog");
            }
            catch (RunException re)
            {
                MensajesError(re.Message, re, "GuardarExceptionLog");
            }

        }
        private void MensajesError(String msgUsu, Exception ex, String metError)
        {
            Crosland.Automotriz.Web.UserControl.MensajeError uc = (Crosland.Automotriz.Web.UserControl.MensajeError)Master.FindControl("ucErrorMensaje");
            String msgReal, fhError, pagError, codUsu;
            msgReal = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
            pagError = new System.IO.FileInfo(Page.Request.Url.AbsolutePath).Name;
            codUsu = Session["User"].ToString();
            fhError = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
            int number = 0;
            for (int i = 0; i < trace.FrameCount; i++)
            {
                System.Diagnostics.StackFrame sf = trace.GetFrame(i);
                number = sf.GetFileLineNumber();
            }
            uc.Errores(msgUsu, msgReal, fhError, pagError, metError, codUsu, number);
        }

        protected void dgDetallePedido_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            this.ListaDetalle();
        }

        protected void btnexport_Click(object sender, EventArgs e)
        {
            int nroPronostico = Convert.ToInt32(Session["nro_pronostico"]);


            this.rvPopupReporte.ProcessingMode = ProcessingMode.Remote;
            this.rvPopupReporte.ShowCredentialPrompts = true;
            this.rvPopupReporte.ShowExportControls = true;
            this.rvPopupReporte.ServerReport.ReportServerCredentials = new RSCredentials();
            this.rvPopupReporte.ServerReport.ReportServerUrl =
                new Uri(ConfigurationManager.AppSettings[DatosConfiguracion.RsServer]);
            this.rvPopupReporte.ServerReport.ReportPath = "/SAP_Repuestos/rs_Rep_PedidoImportacion";

            ReportParameter parameter = new ReportParameter("nro_pronostico", nroPronostico.ToString());

            this.rvPopupReporte.ServerReport.SetParameters(parameter);
        }




        [Serializable]
        public sealed class RSCredentials : IReportServerCredentials
        {
            public WindowsIdentity ImpersonationUser
            {
                get { return null; }
            }

            public ICredentials NetworkCredentials
            {
                get
                {
                    string userName = ConfigurationManager.AppSettings[DatosConfiguracion.RsUser];
                    string password = ConfigurationManager.AppSettings[DatosConfiguracion.RsPassword];
                    string domain = ConfigurationManager.AppSettings[DatosConfiguracion.RsDomain];

                    return new NetworkCredential(userName, password, domain);
                }
            }

            public bool GetFormsCredentials(out Cookie authCookie, out String userName, out String password,
                out String authority)
            {
                authCookie = null;
                userName = null;
                password = null;
                authority = null;
                return false;
            }
        }

        protected void btnSituacionItem_Click(object sender, EventArgs e)
        {
            if (dgDetallePedido.FocusedRowIndex == -1)
                return;

            try
            {
                String COD_MATERIAL = dgDetallePedido.GetRowValues(dgDetallePedido.FocusedRowIndex, "COD_MATERIAL").ToString();
                String ID_MATERIAL = dgDetallePedido.GetRowValues(dgDetallePedido.FocusedRowIndex, "id_material").ToString();
                Session["CODIGO_MATERIAL"] = COD_MATERIAL;
                Session["ID_MATERIAL"] = ID_MATERIAL;
                popupReporte.ShowOnPageLoad = true;
            }
            catch (Exception exe)
            {
                GuardarExceptionLog("Error al seleccionar la grilla pronostico importación ", exe, "btnSituacionItem_Click");
                MensajesError("Error al seleccionar la grilla pronostico importación", exe, "btnSituacionItem_Click");
            }
        }

        protected void btnMostrar_Click(object sender, EventArgs e)
        {
            if (dgDetallePedido.FocusedRowIndex == -1) {
                return;
            }
            this.Mostrar();
        }
        private void Mostrar()
        {

            try
            {
                ActualizarPedidoLogic Actualiza = new ActualizarPedidoLogic();
                string tipoABC = Convert.ToString(dgDetallePedido.GetRowValues(dgDetallePedido.FocusedRowIndex, "TIPO_ABC")).ToLower();
                if (tipoABC == "a" || tipoABC == "b") { RPFormula_A_B.ClientVisible = true; }
                else { RPFormula_C_N_O.ClientVisible = true; }
                int Nro_pronostico = Convert.ToInt32(Session["nro_pronostico"]);
                int ID_MATERIAL = Convert.ToInt32(dgDetallePedido.GetRowValues(dgDetallePedido.FocusedRowIndex, "id_material").ToString());
                lblTotalCan.Text = Convert.ToString(Actualiza.ListarTextoTotal(Nro_pronostico, ID_MATERIAL));
                lblMax.Text = Convert.ToString(Actualiza.countflag(Nro_pronostico, ID_MATERIAL));
                lblTotalPromedioDias.Text = String.Format("{0:0.00}", Actualiza.total_general(Nro_pronostico, ID_MATERIAL));
                lblCant_vta.Text = Convert.ToString(Actualiza.can_vta(Nro_pronostico, ID_MATERIAL));

                lblTotalCNO.Text = String.Format("{0:0.00}", Actualiza.totalCNO(Nro_pronostico, ID_MATERIAL));
                int intNumDiasDiaria = ((Convert.ToInt32(Session["ANO_FIN"]) - Convert.ToInt32(Session["ANO_INI"])) + 1) * 30;
                lblNum_vta.Text = intNumDiasDiaria.ToString();
                this.RecuperarDatosSession();
                dgPronostico.DataSource = Actualiza.ListarPronostico(Nro_pronostico, ID_MATERIAL);
                dgPronostico.DataBind();
                PopupMostrarAna.ShowOnPageLoad = true;
            }
            catch (Crosland.Automotriz.Logic.ControlExeption.DataException ex)
            {
                GuardarExceptionLog(ex.Message, ex, "Mostrar");
                MensajesError(ex.Message, ex, "Mostrar");
            }
            catch (RunException exe)
            {
                GuardarExceptionLog(exe.Message, exe, "Mostrar");
                MensajesError(exe.Message, exe, "Mostrar");
            }
            catch (Exception ex)
            {
                GuardarExceptionLog("Error no controlado en la aplicación", ex, "Mostrar");
                MensajesError("Error no controlado en la aplicación", ex, "Mostrar");

            }

        }

        private void RecuperarDatosSession()
        {
            try
            {

                ActualizarPedidoLogic Actualiza = new ActualizarPedidoLogic();
                int indexF = dgDetallePedido.FocusedRowIndex;
                int Nro_pronostico = Convert.ToInt32(Session["nro_pronostico"]);
                int ID_MATERIAL = Convert.ToInt32(dgDetallePedido.GetRowValues(indexF, "id_material").ToString());

                lblPerioinicial.Text = string.Empty;
                lblPeriodoFinal.Text = string.Empty;

                lblPerioinicial.Text = Session["ANO_MES_INI"].ToString();
                lblPeriodoFinal.Text = Session["ANO_MES_FIN"].ToString();

                lblPSMcantidad.Text = Convert.ToString(Actualiza.ListarTextoTotal(Nro_pronostico, ID_MATERIAL));

                lblCantidadSugerida.Text = String.Format("{0:0.00}", dgDetallePedido.GetRowValues(indexF, "cant_sugerida"));
                lblPSD.Text = Convert.ToString(dgDetallePedido.GetRowValues(indexF, "psd"));
                lblCantidadStock.Text = String.Format("{0:0}", dgDetallePedido.GetRowValues(indexF, "can_stock"));
                lblCantidadTransito.Text = String.Format("{0:0}", dgDetallePedido.GetRowValues(indexF, "can_transito"));
                lblPSM.Text = String.Format("{0:0.00}", dgDetallePedido.GetRowValues(indexF, "psm"));
                lblPeriodosSalidaStock.Text = string.Format("{0:0}", Actualiza.PronosticoImportacionNroDiasReposicion(Nro_pronostico, Convert.ToString(dgDetallePedido.GetRowValues(indexF, "TIPO_ABC"))));
                ls.Text = Convert.ToString(dgDetallePedido.GetRowValues(dgDetallePedido.FocusedRowIndex, "can_stock"));
                lpf.Text = Session["ANO_MES_FIN"].ToString();
                Lsi.Text = Session["ANO_MES_INI"].ToString();
                string numero_meses = Convert.ToString(Actualiza.countflag(Nro_pronostico, ID_MATERIAL));
                lblNumeroMeses.Text = numero_meses;


            }
            catch (Exception e)
            {
                GuardarExceptionLog(e.Message, e, "RecuperarDatosSession");
                MensajesError(e.Message, e, "RecuperarDatosSession");
            }
        }

        protected void dgPronostico_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            try
            {
                ActualizarPedidoLogic Actualiza = new ActualizarPedidoLogic();
                int Nro_pronostico = Convert.ToInt32(Session["nro_pronostico"]);
                int ID_MATERIAL = Convert.ToInt32(dgDetallePedido.GetRowValues(dgDetallePedido.FocusedRowIndex, "id_material").ToString());
                dgPronostico.DataSource = Actualiza.ListarPronostico(Nro_pronostico, ID_MATERIAL);
                dgPronostico.DataBind();
            }
            catch (Exception exe)
            {
                GuardarExceptionLog(exe.Message, exe, "dgPronostico_AfterPerformCallback");
                MensajesError(exe.Message, exe, "dgPronostico_AfterPerformCallback");
            }
        }

        protected void dgPronostico_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
        {

            if (e.RowType != GridViewRowType.Data) return;
            int ind_flag = Convert.ToInt32(e.GetValue("IND_MAX"));
            if (ind_flag == 1)
                e.Row.BackColor = Color.LightPink;
        }

        protected void btnSalir1_Click(object sender, EventArgs e)
        {
            String strNomPage = String.Format("{0}?id={1}", Session["page_origen"], idNegocio);
            Response.Redirect("~/Repuestos/"+strNomPage);
        }

    }
}